<?
if( isset($_POST['users']) )
    $users = explode(',', trim($_POST['users'], ','));
if( isset($_POST['addToGroup']) )
    $addToGroup = trim($_POST['addToGroup'], ',');
if( isset($_POST['deleteFromGroup']) )
    $deleteFromGroup = trim($_POST['deleteFromGroup'], ',');

/*
 Lägg till flera användare till en grupp
*/
function users2group($group, $users) {
	global $conn;

	foreach ($users as $user) {
		$info = ldap_get_entries($conn, ldap_search($conn, $GLOBALS["dc"], "(&(objectClass=person)(uidnumber=$user))"));

		$username = $info[0]['cn'][0];
		$dn = "cn=".$group.",ou=Groups,".$GLOBALS["dc"];
		
		$add['memberuid'] = $username;

		@ldap_mod_add($conn,$dn,$add);
	}
}



if (isset($_POST['addToGroup']) AND ($_POST['addToGroup'])) {
	$group = $addToGroup;
	users2group($group, $users);

        //om inga fel skett
        if( !isset($_SESSION['error']) )
            info('user_mod');
};

if (isset($_POST['addToNewGroup']) AND $_POST['addToNewGroup']) {
	$group = strtolower($_POST['addToNewGroup']);
	exec("/usr/sbin/smbldap-groupadd -a \"$group\" 2> /dev/null", $out, $ret);
	switch($ret) {
	case 9:
                error("gruppen existerar redan");
                break;
        case 0:
                $change["description"] = $group;
                $dn = "cn=$group,ou=groups,".$GLOBALS["dc"];
                ldap_mod_add($conn,$dn,$change);

		users2group($group, $users);

                //om inga fel skett
                if( !isset($_SESSION['error']) )
                    info('user_mod');
                break;
        default:
                error("unknown_ldap");
	};
}

if (isset($_POST['deleteFromGroup']) AND $_POST['deleteFromGroup']) {
	$group = $deleteFromGroup;
	foreach ($users as $user) {
		$info = ldap_get_entries($conn, ldap_search($conn, $GLOBALS["dc"], "(&(objectClass=person)(uidnumber=$user))"));

		$username = $info[0]['cn'][0];
		$dn = "cn=".$group.",ou=Groups,".$GLOBALS["dc"];

		$delete["memberuid"] = $username;
		@ldap_mod_del($conn,$dn,$delete);
	}
        
        //om inga fel skett
        if( !isset($_SESSION['error']) )
            info('user_mod');
};

?>
